<?php

namespace App\Http\Controllers;

use App\Exceptions\AppException;
use App\Exceptions\AuthException;
use App\Libs\Sms\Sms;
use App\Models\DataDict;
use App\Models\District;
use App\Services\UserService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class DictController extends Controller
{
    /**
     * 字典列表
     */
    public function list(Request $request)
    {
        $user = Auth::user();
        if (!$user->hasPermissionTo('dict')) {
            throw new AuthException();
        }

        $query = DataDict::query();
        if ($user->district_id == District::CITY_ID) {
            //市级账号
            $query->where(['type' => DataDict::TYPE_CITY]);
        } else {
            //区县级账号
            $query->where(['type' => DataDict::TYPE_DISTRICT, 'district_id' => $user->district_id]);
        }
        if (!empty($request->id)) {
            $query->where(['id' => $request->id]);
        }
        if (!empty($request->dict_code)) {
            $query->where('dict_code', 'like', "%{$request->dict_code}%");
        }
        if (!empty($request->category_code)) {
            $query->where(['category_code' => $request->category_code]);
        }
        if (!empty($request->category_desc)) {
            $query->where(['category_desc' => $request->category_desc]);
        }
        if ($request->status !== '' && $request->status !== NULL) {
            $query->where(['status' => $request->status]);
        }

        $pageSize = isset($request->page_size) ? $request->page_size : 10;
        $response = $query->orderBy('order', 'asc')->paginate($pageSize);
        return responder()->success($response);
    }

    public function categoryList()
    {
        $user = Auth::user();
        if (!$user->hasPermissionTo('dict')) {
            throw new AuthException();
        }

        $query = DataDict::query()->where(['status' => DataDict::STATUS_ENABLED]);
        if ($user->district_id == District::CITY_ID) {
            //市级账号
            $query->where(['type' => DataDict::TYPE_CITY]);
        } else {
            //区县级账号
            $query->where(['type' => DataDict::TYPE_DISTRICT]);
        }

        $cateogryCodeList = $query->select(['category_code'])->groupBy('category_code')->get()->toArray();
        if (empty($cateogryCodeList)) {
            return responder()->success([]);
        }

        $result = [];
        foreach ($cateogryCodeList as $v) {
            $result[] = DataDict::query()->select(['category_code', 'category_desc'])->where(['category_code' => $v['category_code']])->first()->toArray();
        }
        return responder()->success($result);
    }

    /**
     * 创建字典
     */
    public function create(Request $request)
    {
        $user = Auth::user();
        if (!$user->hasPermissionTo('dict')) {
            throw new AuthException();
        }

        $request->validate([
            'dict_code' => ['required'],
            'category_code' => ['required', 'exists:data_dicts,category_code'],
            'extra' => 'nullable|array',
            'district_id' => ['exists:districts,id'],
            'status' => 'in:0,1'
        ], [
            'dict_code.required' => '字典值不能为空',
            'category_code.required' => '分类编码不能为空',
            'category_code.exists' => '分类编码不正确',
            'extra.json' => '其他属性不正确',
            'district_id.exists' => '区县ID不正确',
            'status.in' => 'status不正确'
        ]);

        $dict2 = DataDict::where(['category_code' => $request->category_code])->first();
        UserService::checkRoleType($user->district_id, $dict2->type);

        $model = new DataDict();
        $model->type = $dict2->type;
        $districtId = null;
        $condition = ['dict_code' => $request->dict_code, 'category_code' => $request->category_code, 'type' => $dict2->type];
        if ($dict2->type == DataDict::TYPE_CITY) {
            !empty($request->district_id) && $districtId = $request->district_id;
        } else {
            $districtId = $user->district_id;
            $condition['district_id'] = $districtId;
        }
        $model->district_id = $districtId;

        $dict1 = DataDict::where($condition)->first();
        if ($dict1) {
            throw new AppException('字典值已经存在');
        }

        $model->dict_code = $request->dict_code;
        $model->dict_desc = $model->dict_code;
        $model->category_code = $request->category_code;
        $model->category_desc = $dict2->category_desc;
        if ($request->status !== '' && $request->status !== NULL) {
            $model->status = $request->status;
        } else {
            $model->status = DataDict::STATUS_ENABLED;
        }
        !empty($request->extra) && $model->extra = $request->extra;
        !empty($request->order) && $model->order = $request->order;
        $model->save();

        return responder()->success($model);
    }

    /**
     * 编辑字典
     */
    public function update(Request $request)
    {
        $user = Auth::user();
        if (!$user->hasPermissionTo('dict')) {
            throw new AuthException();
        }

        $request->validate([
            'id' => ['exists:data_dicts,id'],
            'dict_code' => ['required'],
            'category_code' => ['required', 'exists:data_dicts,category_code'],
            'extra' => 'nullable|array',
            'status' => 'in:0,1'
        ], [
            'id.exists' => '字典id不正确',
            'dict_code.required' => '字典值不能为空',
            'extra.json' => '其他属性不正确',
            'category_code.required' => '分类编码不能为空',
            'category_code.exists' => '分类编码不正确',
            'status.in' => 'status不正确'
        ]);

        $dict2 = DataDict::where(['category_code' => $request->category_code])->first();

        if ($user->district_id == District::CITY_ID) {
            //市账号
            $model = DataDict::where(['id' => $request->id, 'type' => DataDict::TYPE_CITY])->first();
        } else {
            //区县账号只能改本区县的
            $model = DataDict::where(['id' => $request->id, 'type' => DataDict::TYPE_DISTRICT, 'district_id' => $user->district_id])->first();
        }
        if (empty($model)) {
            throw new AuthException();
        }

        $condition = ['dict_code' => $request->dict_code, 'category_code' => $request->category_code, 'type' => $dict2->type];
        if ($dict2->type == DataDict::TYPE_CITY) {
        } else {
            $condition['district_id'] = $user->district_id;
        }
        $dict1 = DataDict::where($condition)
            ->where('id', '!=', $request->id)
            ->first();
        if ($dict1) {
            throw new AppException('字典值已经存在');
        }

        $model->category_code = $request->category_code;
        $model->category_desc = $dict2->category_desc;
        $model->dict_code = $request->dict_code;
        $model->dict_desc = $model->dict_code;
        if ($request->status !== '' && $request->status !== NULL) {
            $model->status = $request->status;
        }
        !empty($request->extra) && $model->extra = $request->extra;
        $model->save();

        return responder()->success($model);
    }

    /**
     * 字典详情
     */
    public function show(Request $request)
    {
        $user = Auth::user();
        if (!$user->hasPermissionTo('dict')) {
            throw new AuthException();
        }

        if (empty($request->id) && (empty($request->dict_code || empty($request->category_code)))) {
            throw new AppException('参数不正确');
        }

        $query = DataDict::query();
        if ($user->district_id == District::CITY_ID) {
            //市级账号
            $query->where(['type' => DataDict::TYPE_CITY]);
        } else {
            //区县级账号
            $query->where(['type' => DataDict::TYPE_DISTRICT, 'district_id' => $user->district_id]);
        }

        if (!empty($request->id)) {
            $query->where(['id' => $request->id]);
        } else {
            $query->where(['dict_code' => $request->dict_code, 'category_code' => $request->category_code]);
        }

        $model = $query->first();
        return responder()->success($model);
    }

    /**
     * 删除字典
     */
    public function delete(Request $request)
    {
        $user = Auth::user();
        if (!$user->hasPermissionTo('dict')) {
            throw new AuthException();
        }

        if (empty($request->id)) {
            throw new AppException('id不能为空');
        }

        $query = DataDict::query();
        if ($user->district_id == District::CITY_ID) {
            //市级账号
            $query->where(['type' => DataDict::TYPE_CITY]);
        } else {
            //区县级账号
            $query->where(['type' => DataDict::TYPE_DISTRICT, 'district_id' => $user->district_id]);
        }
        $model = $query->where(['id' => $request->id])->first();
        if (empty($model)) {
            throw new AuthException();
        }

        $model->delete();
        return responder()->success([]);
    }
}
